package org.mybatis.generator.extend.servicegenerator;

import org.mybatis.generator.api.dom.java.*;

import java.util.Set;
import java.util.TreeSet;

/**
 * service实现查询方法构造
 */
public class SelectAllByEntitySelectiveMethodOfServiceGenerator extends AbstractJavaServiceMethodGenerator {

	public SelectAllByEntitySelectiveMethodOfServiceGenerator(boolean isSimple) {
		super();
	}

	@Override
	public void addServiceElements(TopLevelClass topLevelClass) {
		Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
		topLevelClass.addImportedType("com.github.pagehelper.PageInfo");
		topLevelClass.addImportedType("com.github.pagehelper.PageHelper");
		topLevelClass.addImportedType("java.util.List");
		
		Method method = new Method();
		method.setVisibility(JavaVisibility.PUBLIC);
		String rt = introspectedTable.getRules().calculateAllFieldsClass().getShortName();
		FullyQualifiedJavaType returnType = new FullyQualifiedJavaType("List<" + rt + ">");
		method.setReturnType(returnType);
		//importedTypes.add(returnType);
		method.addAnnotation("@Override");
		method.setName(introspectedTable.getSelectAllSelectiveStatementId());
		
		// 参数设置
		FullyQualifiedJavaType parameterType1 = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
		FullyQualifiedJavaType parameterType2 = new FullyQualifiedJavaType("Integer");
		FullyQualifiedJavaType parameterType3 = new FullyQualifiedJavaType("Integer");
		String parameterName1 = "record";
		String parameterName2 = "pageNum";
		String parameterName3 = "pageSize";
		method.addParameter(new Parameter(parameterType1, parameterName1));
		method.addParameter(new Parameter(parameterType2, parameterName2));
		method.addParameter(new Parameter(parameterType3, parameterName3));
		
		
		// 方法内容
		FullyQualifiedJavaType mapper = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaMapperType());
		StringBuffer bodyLineSB = new StringBuffer();
		bodyLineSB.append("PageHelper.startPage(" + parameterName2 +", " + parameterName3 + ");");
		bodyLineSB.append("\r\t\t");
		bodyLineSB.append("List<" + parameterType1.getShortName() + "> list = ");
		String shortName = mapper.getShortName();
		shortName = shortName.substring(0, 1).toLowerCase() + shortName.substring(1);
		bodyLineSB.append(shortName + "." + introspectedTable.getSelectAllSelectiveStatementId());
		bodyLineSB.append("(").append(parameterName1).append(");");
		bodyLineSB.append("\r\t\t");
		bodyLineSB.append("return list;");
		method.addBodyLine(bodyLineSB.toString());

		method.addJavaDocLine("/** 根据条件动态查询 */");
		context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);

		if (context.getPlugins().clientSelectByPrimaryKeyMethodGenerated(method, topLevelClass, introspectedTable)) {
			topLevelClass.addImportedTypes(importedTypes);
			topLevelClass.addMethod(method);
		}
	}

}
